﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
namespace Ccteg.Common
{

    /// <summary>
    /// 树结构帮助类
    /// </summary>
    public class TreeHelper
    {


        /// <summary>
        /// 建造树结构
        /// </summary>
        /// <param name="allNodes">所有的节点</param>
        /// <param name="parentId">parentId</param>
       /// <returns></returns>
        public static List<Tree_ViewModel> BuildTree(List<Tree_ViewModel> allNodes,   string parentId = "0")
        {
            List<Tree_ViewModel> nodes = new List<Tree_ViewModel>();
            Func<string, List<Tree_ViewModel>> GetTree = null;
            GetTree = new Func<string, List<Tree_ViewModel>>((parentid) =>
                     {
                         var r = allNodes.Where(p => p.ParentId == parentid).ToList();
                         if (r.Count() > 0)
                         {
                             foreach (var item in r)
                             {
                                 item.children = GetTree(item.Id);
                             }
                         }
                         return r;
                     });
          
            return GetTree(parentId);
        }

        /// <summary>
        /// 转换为一级
        /// </summary>
        /// <param name="allNodes"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public static List<Tree_ViewModel> BuildTreeForMatFrist(List<Tree_ViewModel> allNodes,string parentId = "0")
        {
            List<Tree_ViewModel> nodes = new List<Tree_ViewModel>();
            Func<string, List<Tree_ViewModel>> GetTree = null;
            GetTree = new Func<string, List<Tree_ViewModel>>((parentid) =>
            {
                var r = allNodes.Where(p => p.ParentId == parentid).ToList();
                if (r.Count() > 0)
                {
                    foreach (var item in r)
                    {
                        nodes.Add(item);
                        GetTree(item.Id);
                    }
                }
                return r;
            });
            GetTree(parentId);
            return nodes;
        }

    }
}